package controller

import (
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"library/Vo"
	"library/common"
	"library/config"
	"library/model"
	"log"
	"net/http"
)

func Borrow(ctx *gin.Context) {
	//借阅 1.更改相关书籍借阅状态；2.增加用户借阅记录
	u, exists := ctx.Get("user")
	if !exists {
		Vo.ResponseFiled(ctx, common.StatusNotLogin, "用户未登录")
		return
	}
	user := u.(model.User)

	bookIdentityId := ctx.PostForm("identity_id")

	db := config.GetDB()
	tx := db.Begin()
	var book model.Book
	err := tx.Where("identity_id = ?", bookIdentityId).First(&book).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		Vo.ResponseFiled(ctx, common.StatusBookNotFound, "书籍不存在")
		return
	}

	if book.BorrowStatus {
		Vo.ResponseFiled(ctx, common.StatusBorrowErr, "书籍目前不在馆")
		return
	}

	// 新增借阅记录
	borrowRecord := model.UserBorrow{
		UserId: user.ID,
		BookId: book.ID,
	}
	if rows := tx.Create(&borrowRecord).RowsAffected; rows == 0 {
		Vo.ResponseFiled(ctx, common.StatusBorrowErr, "借阅失败，请重试")
		tx.Rollback()
		return
	}

	//更新书籍借阅状态
	if rows := tx.Model(&book).Update("borrow_status", true).RowsAffected; rows == 0 {
		Vo.ResponseFiled(ctx, common.StatusBorrowErr, "借阅失败，请重试")
		tx.Rollback()
		return
	}

	responseData := gin.H{"book":book}
	Vo.ResponseSuccess(ctx, common.StatusBorrowSuccess, responseData, "借阅成功")
	tx.Commit()	//提交事务，借书成功
}

func ReturnBook(ctx *gin.Context) {
	//还书
	_, exists := ctx.Get("user")
	if !exists {
		Vo.ResponseFiled(ctx, common.StatusNotLogin, "用户未登录")
		return
	}

	bookIdentityId := ctx.PostForm("identity_id")

	db := config.GetDB()
	tx := db.Begin()
	var book model.Book
	err := tx.Where("identity_id = ?", bookIdentityId).First(&book).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		Vo.ResponseFiled(ctx, common.StatusBookNotFound, "书籍不存在")
		return
	}
	// 删除借阅记录
	var borrowRecord model.UserBorrow
	err = tx.Where("book_id = ?", book.ID).First(&borrowRecord).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		Vo.ResponseFiled(ctx, common.StatusBookNotFound, "还书失败，请重试")
		log.Println("查询不到借阅记录")
		tx.Rollback()
		return
	}
	if rows := tx.Delete(&borrowRecord).RowsAffected; rows == 0 {
		Vo.ResponseFiled(ctx, common.StatusReturnErr, "还书失败，请重试")
		log.Println("删除借阅记录失败")
		tx.Rollback()
		return
	}
	//更新书籍借阅状态
	if rows := tx.Model(&book).Update("borrow_status", false).RowsAffected; rows == 0 {
		Vo.ResponseFiled(ctx, common.StatusBorrowErr, "更新书籍状态，还书失败，请重试")
		tx.Rollback()
		return
	}

	responseData := gin.H{"book":book}
	Vo.ResponseSuccess(ctx, common.StatusBorrowSuccess, responseData, "还书成功")
	tx.Commit()	//提交事务，还书成功
}

func Info(ctx *gin.Context) {
	user, _ := ctx.Get("user")
	ctx.JSON(http.StatusOK, gin.H{
		"code" : common.StatusGetUserInfo,
		"data" : gin.H{"user":Vo.NewUserVo(user.(model.User))},
	})
}